<?php

namespace Home\Controller;

use Think\Controller;
use Think\Log;

class BaseController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function check_login()
    {
        $isLong = $this->checkLong();
        if ($isLong === false) {
            $this->redirect('user/login');
        } else {
            session("user_id", $isLong['id']);
            return $isLong['id'];
        }

        // $user_id = session("user_id");
        // if (!$user_id) {
        //     $this->redirect('user/login');
        // } else {
        //     return $user_id;
        // }
    }

    /**
     * 验证用户登录时效问题
     * @return [type] [description]
     */
    public function checkLong()
    {
        $arr                      = [];
        $now                      = time();
        if(!isset($_COOKIE['auth']))
            return false;

        list($identifier, $token) = explode(':', $_COOKIE['auth']);
        Log::write('identifier:'.$identifier);
        Log::write('token:'.$token);
        if (ctype_alnum($identifier) && ctype_alnum($token)) {
            $arr['identifier'] = $identifier;
            $arr['token']      = $token;
        } else {
            return false;
        }

        $user = M("user");
        $info = $user->where(['identifier' => $arr['identifier']])->find();
        if ($info != null) {
            if ($arr['token'] != $info['token']) {
                return false;
            } else if ($now > $info['timeout']) {
                return false;
            } else {
                return $info;
            }
        } else {
            return false;
        }
    }
}
